package edu.dayu.controller;

import edu.dayu.pojo.User;
import edu.dayu.service.UserService;
import edu.dayu.util.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("admin")
    public String toLogin(){
        return "admin/login";
    }

    @PostMapping("login")
    public String Login(String username, String password, HttpSession session, RedirectAttributes attributes){
        User user = new User(username, Md5Util.code(password));
        User login = userService.Login(user);
        if (login!=null) {
            session.setAttribute("user", login);
            return "redirect:bIndex.html";
        }else{
            attributes.addFlashAttribute("msg","用户名或密码错误");
            return "redirect:/admin";
        }
    }

    @GetMapping("logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/admin";
    }
}
